//
//  Common.m
//  GL
//
//  Created by 王亚陆 on 16/1/12.
//  Copyright © 2016年 知车. All rights reserved.
//

#import "Common.h"
//#import "AFNetworking.h"
//#import <AFNetworking.h>
#import <AFNetworking/AFNetworking.h>

#import "UIImageView+WebCache.h"
#import "Header.h"
#import <Masonry.h>
#import <SystemConfiguration/SystemConfiguration.h>
#import "MBProgressHUD.h"
#import "LoginViewController.h"

@implementation Common
{
    DownloadFinishedBlock _finishedBlock;
    DownloadFailedBlock _failedBlock;
}


//提示框
-(UIImageView*)createUIImage:(NSString *)title andDelay:(float)delay {
    
    UILabel * label =[[UILabel alloc]init];
    label.text = title;
    label.tag = 88;

    label.textAlignment = NSTextAlignmentCenter;
    UIFont *fnt = [UIFont fontWithName:@"HelveticaNeue" size:FontOfSize15];
    label.textColor = [UIColor whiteColor];
    CGSize size = [label.text sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:fnt,NSFontAttributeName, nil]];
    
    // 名字的H
    CGFloat nameH = size.height;
    // 名字的W
    CGFloat nameW = size.width;
    
    
    label.frame =CGRectMake(0, 0, nameW, nameH);
    label.font = Font(FontOfSize15);

    UIImageView * imageCollect = [[UIImageView alloc]init];
    imageCollect.image = [UIImage imageNamed:@"project_product_collect_jiaohu"];
    imageCollect.frame = CGRectMake(0, 0, 90+label.frame.size.width, 41);
    imageCollect.alpha = 0.5;
    imageCollect.tag = 100;
    
    
    [imageCollect addSubview:label];
    //收藏成功提示
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(imageCollect.mas_centerX);
        make.centerY.equalTo(imageCollect.mas_centerY);
    }];
    
    [self performSelector:@selector(CollectDissMi:) withObject:imageCollect afterDelay:delay];
    

    return imageCollect;
}
-(void)CollectDissMi:(UIImageView*)sender{
    
    [sender  removeFromSuperview];
}

//点击button
-(UIButton*)createBtn:(NSString *)title andFont:(long)font andTag:(NSInteger)tag and:(UIViewController *)target action:(SEL)action andTitleColor:(UIColor *)color andBorderColor:(UIColor*)borderColor andBackgroundColor:(UIColor*)backgroundColor{
    
    UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setTitle:title forState:UIControlStateNormal];
    btn.layer.borderWidth = 0.5;
    btn.layer.borderColor = borderColor.CGColor;
    btn.titleLabel.font = Font(font);
    btn.backgroundColor = backgroundColor;
    if (color) {
        [btn setTitleColor:color forState:UIControlStateNormal];
    }else{
        [btn setTitleColor:BlackColor forState:UIControlStateNormal];
    }
    btn.tag = tag;
    [btn addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
    return btn;
 
}
//text自适应宽高
-(UILabel*)createUIlabel:(NSString *)title andFont:(CGFloat)font andColor:(UIColor *)color{
    
        UILabel * label =[[UILabel alloc]init];
        label.text = title;
        label.textAlignment = NSTextAlignmentCenter;
        label.textColor = color;
        UIFont *fnt = [UIFont fontWithName:@"HelveticaNeue" size:font];CGSize size = [label.text sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:fnt,NSFontAttributeName, nil]];
        // 名字的H
        CGFloat nameH = size.height;
        // 名字的W
        CGFloat nameW = size.width;
    
        label.textAlignment = NSTextAlignmentLeft;
        label.frame =CGRectMake(0, 0, nameW, nameH);
        label.font = Font(font)
        return label;
}

+(BOOL)judgeUsertype
{
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString *string = [user objectForKey:@"userType"];
    
    if ([string isEqualToString:@"50"]) {
        
        return YES;
    } else {
        return NO;
    }

}


//tableview多余的线隐藏
+(void)setExtraCellLindeHidder:(UITableView *)tableView
{
    UIView *view=[UIView new];
    view.backgroundColor=[UIColor clearColor];
    [tableView setTableFooterView:view];
}

//设置导航专用按钮
-(void)customNavigationItem:(UIViewController *)target position:(item_position)position title:(NSString *)title image:(UIImage *)image action:(SEL)action{
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
    btn.frame = CGRectMake(0, 0, 60, 30);
    [btn setTitle:title forState:UIControlStateNormal];
    [btn setBackgroundImage:image forState:UIControlStateNormal];
    [btn addTarget:self action:action forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:btn];
    if (position == item_left) {
        target.navigationItem.leftBarButtonItem = item;
    } else {
        target.navigationItem.rightBarButtonItem = item;
    }
}

-(UIView*)call:(NSString *)iphone and:(UIViewController *)target action:(SEL)action{
    
    UIView * backView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, Main_Width, Main_height)];
    backView.tag = 1000;
    backView.backgroundColor = RGBACOLOR(0, 0, 0, 0.3);
    
    UIImageView * imageIphone = [[UIImageView alloc]initWithFrame:CGRectMake(14, 271, Main_Width-28, 125)];
    imageIphone.image = [UIImage imageNamed:@"common_400call_background"];
    imageIphone.tag = 2000;
    imageIphone.userInteractionEnabled = YES;
    imageIphone.hidden = YES;
    imageIphone.layer.cornerRadius=20/3.0;
    imageIphone.layer.masksToBounds=YES;
    imageIphone.backgroundColor = [UIColor whiteColor];
    UILabel * title1 = [[UILabel alloc]init];
    title1.text = @"咨询投诉、手艺人入驻可拨打客服电话。";
    title1.textColor = RGBACOLOR(149, 149, 149, 1);
    title1.textAlignment = NSTextAlignmentCenter;
    UILabel * title2 = [[UILabel alloc]init];
    title2.textColor = RGBACOLOR(149, 149, 149, 1);
    title2.text = @"客服时间：7X24小时";
    title2.textAlignment = NSTextAlignmentCenter;
    title2.font = Font(FontOfSize12);
    title1.font = Font(FontOfSize12);
    [imageIphone addSubview:title1];
    [imageIphone addSubview:title2];
    
    [title1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(imageIphone.mas_left).with.offset(65);
        make.right.equalTo(imageIphone.mas_right).with.offset(-65);
        make.top.equalTo(imageIphone.mas_top).with.offset(20);
    }];
    [title2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(imageIphone.mas_left).with.offset(100);
        make.right.equalTo(imageIphone.mas_right).with.offset(-100);
        make.top.equalTo(title1.mas_bottom).with.offset(8);
    }];
//    UIImageView * image1 = [[UIImageView alloc]init];
//    image1.image = [UIImage imageNamed:@"common_list_line1"];
//    [backView addSubview:image1];
//    [image1 mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.equalTo(imageIphone.mas_left).with.offset(117);
//        make.right.equalTo(imageIphone.mas_right).with.offset(-117);
//        make.top.equalTo(title1.mas_bottom).with.offset(15);
//    }];
//    
    UIButton * cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
    cancelBtn.tag = 1000;
    [cancelBtn setTitleColor:RGBACOLOR(149, 149, 149, 1) forState:UIControlStateNormal];
    cancelBtn.titleLabel.font = Font(17);
    [cancelBtn addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
    UIButton * dialBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [dialBtn setTitle:@"确定" forState:UIControlStateNormal];
    [dialBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    dialBtn.tag = 2000;
    dialBtn.titleLabel.font = Font(17);
    [dialBtn addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
    
    [imageIphone addSubview:cancelBtn];
    [imageIphone addSubview:dialBtn];
    [cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(imageIphone.mas_left).with.offset(66);
        make.size.mas_equalTo(CGSizeMake(40, 30));
        make.bottom.equalTo(imageIphone.mas_bottom).with.offset(-15);
    }];
    [dialBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(imageIphone.mas_right).with.offset(-66);
        make.size.mas_equalTo(CGSizeMake(40, 30));
        make.bottom.equalTo(imageIphone.mas_bottom).with.offset(-15);
    }];

    
    
    imageIphone.hidden = NO;
    [backView addSubview:imageIphone];

    return backView;
}
-(UIView*)noInternet:(NSString *)title and:(UIViewController *)target action:(SEL)action andCGreck:(CGRect)frame
{
    
    UIView * backview = [[UIView alloc]initWithFrame:frame];
    backview.backgroundColor = [UIColor whiteColor];
    UILabel * label = [[UILabel alloc]init];
    label.text = @"当前网络不可用，请稍后尝试";
    UIFont *fnt = [UIFont fontWithName:@"HelveticaNeue" size:12.0f];
    CGSize size = [label.text sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:fnt,NSFontAttributeName, nil]];
    label.textColor = RGBACOLOR(149, 149, 149, 1);
    // 名字的H
    CGFloat nameH = size.height;
    // 名字的W
    CGFloat nameW = size.width;
    label.frame =CGRectMake(0, 0, nameW, nameH);
    label.font = Font(12.0f);
    [backview addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo (backview.mas_centerX);
        make.centerY.mas_equalTo (backview.mas_centerY);
    }];
    
    UIImageView * imageBack = [[UIImageView alloc]init];
    imageBack.image = [UIImage imageNamed:@"jiaohu_duanwang_pic"];
    [backview addSubview:imageBack];
    [imageBack mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo (label.mas_centerX);
        make.size.mas_equalTo(CGSizeMake(76, 75));
        make.bottom.mas_equalTo(label.mas_top).with.offset(-10);
    }];

    UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setBackgroundImage:[UIImage imageNamed:@"jiaohu_duanwang_juxing"] forState:UIControlStateNormal];
    btn.backgroundColor = [UIColor whiteColor];
    [btn addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
    [btn setTitle:@"刷新重试" forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [backview addSubview:btn];
    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo (label.mas_centerX);
        make.size.mas_equalTo(CGSizeMake(100, 35));
        make.top.mas_equalTo(label.mas_bottom).with.offset(10);
    }];

    return backview;
}


-(UIView*)customNavigationItem:(UIViewController *)target action:(SEL)action{
    
    UIView * NaView =[[UIView alloc]initWithFrame:CGRectMake(0, 20, Main_Width, 36)];
    UIButton * btn1 =[UIButton buttonWithType:UIButtonTypeCustom];
    btn1.frame = CGRectMake(14, 8, 28, 28);
    [btn1 setBackgroundImage:[UIImage imageNamed:@"detials_project_top_back"] forState:UIControlStateNormal];
    btn1.tag = 1;
    [btn1 addTarget:self action:action forControlEvents:UIControlEventTouchUpInside];
    [NaView addSubview:btn1];
    UIButton * btn2 =[UIButton buttonWithType:UIButtonTypeCustom];
    btn2.frame = CGRectMake(Main_Width-14-28, 8, 28, 28);
    [btn2 setBackgroundImage:[UIImage imageNamed:@"detials_project_top_share"] forState:UIControlStateNormal];
    btn2.tag = 2;
    [btn2 addTarget:self action:action forControlEvents:UIControlEventTouchUpInside];
    [NaView addSubview:btn2];
    UIButton * btn3 =[UIButton buttonWithType:UIButtonTypeCustom];
    btn3.frame = CGRectMake(Main_Width-14-28-28-15, 8, 28, 28);
    [btn3 setBackgroundImage:[UIImage imageNamed:@"detials_project_top_collect"] forState:UIControlStateNormal];
    btn3.tag = 3;
    [btn3 addTarget:self action:action forControlEvents:UIControlEventTouchUpInside];
    [NaView addSubview:btn3];

    return NaView;
}



- (void)writeToLocal:(NSData *)data {
    NSString *path = [NSHomeDirectory() stringByAppendingFormat:@"/Documents/%@.txt",NSStringFromClass([self class])];
    [data writeToFile:path atomically:YES];
}

- (NSData *)readLocal {
    NSString *path = [NSHomeDirectory() stringByAppendingFormat:@"/Documents/%@.txt",NSStringFromClass([self class])];
    NSLog(@"path:%@",path);
    if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
        return [NSData dataWithContentsOfFile:path];
    }
    return nil;
}


//get 请求
+(void)requestWithUrlString:(NSString *)urlString contentType:(NSString *)type finished:(DownloadFinishedBlock)finishedBlock failed:(DownloadFailedBlock)failedBlock{
    
    AFHTTPRequestOperationManager *manager  = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:type,nil];
    
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy defaultPolicy];
    securityPolicy.allowInvalidCertificates = YES;

    
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString *string = [user objectForKey:login_token];
    
    
    if (string.length > 0) {
        
        [manager.requestSerializer setValue:string forHTTPHeaderField:@"Authorization"];
        
    }
    [manager GET:urlString parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        //可以进行一些其他操作，比如将网络数据NSData写到本地路径
        //执行一些其他操作后，再调用自己的block，方便对程序进行扩展
        
        
        if ([responseObject[@"messageCode"] isEqual:[NSNull null]]) {
            
            
        } else {
        
        if (![responseObject[@"success"] boolValue] && [responseObject[@"messageCode"] isEqualToString:@"5004"]) {
            
            UIViewController *viewC = [[[UIApplication sharedApplication] keyWindow] rootViewController];

                UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:responseObject[@"message"] preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    
//                    [user setObject:nil forKey:login_token];
                    
                    LoginViewController *loginVC = [[LoginViewController alloc]init];
                    UINavigationController * loginNC = [[UINavigationController alloc]initWithRootViewController:loginVC];
                    
                    [viewC presentViewController:loginNC animated:YES completion:nil];
                    
                }];
          
                [alert addAction:action1];
            
#pragma mark push方法跟这一样，只是变变写法
            
            
        } else {
            
            NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
            NSString *string = [user objectForKey:login_token];
            
            
            if (string.length > 0) {
                
                [manager.requestSerializer setValue:string forHTTPHeaderField:@"Authorization"];
                
            }
        }
        }
        
        finishedBlock(responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        //当出现错误信息是 弹出提示框
//        [Common showAlertViewAndAnimated:YES andString:error.localizedDescription];
        [Common showAlertViewAndAnimated:YES andString:@"系统维护中"];

        
        failedBlock(error.localizedDescription);
    }];
}

-(void)choiceDriverAndInteger
{
    UIViewController *viewC = [[[UIApplication sharedApplication] keyWindow] rootViewController];
    
    LoginViewController *loginVC = [[LoginViewController alloc]init];
    UINavigationController * loginNC = [[UINavigationController alloc]initWithRootViewController:loginVC];
    
    [viewC presentViewController:loginNC animated:YES completion:nil];


}


+(void)afPostRequestWithUrlString:(NSString *)urlString parms:(NSDictionary *)dic finishedBlock:(DownloadFinishedBlock)finished failedBlock:(DownloadFailedBlock)failed{
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    //Content-Type 要写成与服务器相匹配的类型,一开始可以不写，error信息中会提示我们Content-Type要写成什么
    //manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", nil];
    //实现基本的post请求,函数的参数:为请求地址，和带有post请求参数的字典
    
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy defaultPolicy];
    securityPolicy.allowInvalidCertificates = YES;
    
    
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString *string = [user objectForKey:login_token];
    
    
    if (string.length > 0) {
        
        [manager.requestSerializer setValue:string forHTTPHeaderField:@"Authorization"];
        
    }


    [manager POST:urlString parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {
        //调用自己定义的block
        
        
       NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
 
        if ([dictionary[@"messageCode"] isEqual:[NSNull null]]) {
            
            finished(responseObject);

        } else {

        
        if (![dictionary[@"success"] boolValue] && [dictionary[@"messageCode"] isEqualToString:@"5004"]) {
            
            UIViewController *viewC = [[[UIApplication sharedApplication] keyWindow] rootViewController];
            
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:responseObject[@"message"] preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
//                [user setObject:nil forKey:login_token];

                
                LoginViewController *loginVC = [[LoginViewController alloc]init];
                UINavigationController * loginNC = [[UINavigationController alloc]initWithRootViewController:loginVC];
                
                [viewC presentViewController:loginNC animated:YES completion:nil];
                
            }];
            
            [alert addAction:action1];
            
        } else {
           
            finished(responseObject);

        }
        }
        

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        //当出现错误信息是 弹出提示框
//        [Common showAlertViewAndAnimated:YES andString:error.localizedDescription];
        [Common showAlertViewAndAnimated:YES andString:@"系统维护中"];

        
        //捕捉错误信息
        failed(error.localizedDescription);
    }];
}

//post 请求

- (void)afPostRequestWithUrlString:(NSString *)urlString parms:(NSDictionary *)dic finishedBlock:(DownloadFinishedBlock)finished failedBlock:(DownloadFailedBlock)failed{
    if (_finishedBlock!=finished) {
        _finishedBlock = nil;
        _finishedBlock = finished;
    }
    if (_failedBlock!=failed) {
        _failedBlock = nil;
        _failedBlock = failed;
    }
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    //Content-Type 要写成与服务器相匹配的类型,一开始可以不写，error信息中会提示我们Content-Type要写成什么
    //manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", nil];
    //实现基本的post请求,函数的参数:为请求地址，和带有post请求参数的字典
    
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy defaultPolicy];
    securityPolicy.allowInvalidCertificates = YES;
    
    
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString *string = [user objectForKey:login_token];

    if (string.length > 0) {
        
        [manager.requestSerializer setValue:string forHTTPHeaderField:@"Authorization"];

    }
    
    
    [manager POST:urlString parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {
        //调用自己定义的block
        
        NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        
        if ([dictionary[@"messageCode"] isEqual:[NSNull null]]) {
            
            finished(responseObject);

        } else {

        if (![dictionary[@"success"] boolValue] && [dictionary[@"messageCode"] isEqualToString:@"5004"]) {
            
            UIViewController *viewC = [[[UIApplication sharedApplication] keyWindow] rootViewController];
            
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:responseObject[@"message"] preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
                
//                [user setObject:nil forKey:login_token];

                
                LoginViewController *loginVC = [[LoginViewController alloc]init];
                UINavigationController * loginNC = [[UINavigationController alloc]initWithRootViewController:loginVC];
                
                [viewC presentViewController:loginNC animated:YES completion:nil];
                
            }];
            
            [alert addAction:action1];
            
        } else {
            
            finished(responseObject);
            
        }

        }
    
//        _finishedBlock(responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    
        //当出现错误信息是 弹出提示框
//        [Common showAlertViewAndAnimated:YES andString:error.localizedDescription];
        [Common showAlertViewAndAnimated:YES andString:@"系统维护中"];

        
        //捕捉错误信息
        _failedBlock(error.localizedDescription);
    }];
}
//下载图片
/**调用的方法
 UIImageView *image=[[UIImageView alloc]initWithFrame:CGRectMake(100, 300, 200, 200)];
 //    image.image=[com loadImage:@"http://p22.tuan800.net/pic/movie/434840-iosm1_1431575980884"];
 //    image.backgroundColor=[UIColor cyanColor];
 //    [self.view addSubview:image];
 */
-(UIImage*)loadImage:(NSString *)HttpImage
{
    NSURL *ulr=[NSURL URLWithString:HttpImage];
    
    UIImage *image=[UIImage imageWithData:[NSData dataWithContentsOfURL:ulr]];
    
    return image;
}


//上传图片
- (void)afUploadImageWithUrlString:(NSString *)urlString parms:(NSDictionary *)dic  imageData:(NSData *)data imageKey:(NSString *)key finishedBlock:(DownloadFinishedBlock)finished failedBlock:(DownloadFailedBlock)failed{
    if (_finishedBlock!=finished) {
        _finishedBlock = nil;
        _finishedBlock = finished;
    }
    if (_failedBlock!=failed) {
        _failedBlock = nil;
        _failedBlock = failed;
    }
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", nil];
    //上传图片的post方法
    [manager POST:urlString parameters:dic constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        //利用formData 实现图片上传(可以类比ASI的setData......方法)
        //FileData 图片转换成的NSData
        //name 服务端规定的参数 pis
        //fileName  临时名称
        //mimeType data的文件类型
        [formData appendPartWithFileData:data name:key fileName:@"test.png" mimeType:@"image/png"];
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        _finishedBlock(responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        _failedBlock(error.localizedDescription);
    }];
}


+(CGRect)myRectWithX:(CGFloat)x Y:(CGFloat)y width:(CGFloat)width height:(CGFloat)height;
{
    CGFloat myx=[UIScreen mainScreen].bounds.size.width/375.0;
    CGFloat myy=[UIScreen mainScreen].bounds.size.height/667.0;
    return CGRectMake(x*myx, y*myy, width*myx, height*myy);
}
//登录
+(void)writePhone:(NSString *)phone writeAccount:(NSString *)account writeSecret:(NSString *)secret  writeToken:(NSString *)token remember:(BOOL)isRemembe
{
    NSUserDefaults * userDefaults=[NSUserDefaults standardUserDefaults];
    if (isRemembe) {
        if (account&&secret) {
            [userDefaults setObject:account forKey:@"account"];
            [userDefaults setObject:secret forKey:@"secret"];
        }
        if (phone) {
            [userDefaults setObject:phone forKey:@"phone"];
        }
    }
    else
    {
        if (account) {
            [userDefaults setObject:account forKey:@"account"];
        }
        if (phone) {
            [userDefaults setObject:phone forKey:@"phone"];
        }
    }
    
    [userDefaults setObject:token forKey:@"token"];
    [userDefaults synchronize];
    NSArray * arr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString * path = [arr objectAtIndex:0];
    NSLog(@"userDefaults:%@",path);
}
+(NSDictionary*)backToken
{
    NSMutableDictionary *dic=[[NSMutableDictionary alloc]init];
    
    NSUserDefaults *UserDefaults =[NSUserDefaults standardUserDefaults];
    NSString*string=[UserDefaults objectForKey:@"token"];
    [dic setObject:string forKey:@"token"];
    return dic;
}


//将NSDictionary或者NSArray转化为NSString
+(NSString*)JSONString:(id)theDic;
{
    //保存数组
    NSError *errArr;
    NSData *dataArr=[NSJSONSerialization dataWithJSONObject:theDic options:NSJSONWritingPrettyPrinted error:&errArr];
    NSString *jsonArr=[[NSString alloc]initWithData:dataArr encoding:NSUTF8StringEncoding];
    
    return jsonArr;
}
// 将字典或者数组转化为字符串
+(id)theData:(NSString*)JSONString;
{
    //字符串转化成data类型
    NSData *dataDic=[JSONString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *errDic;
    
    //将data类型转化成字典
    id jsonObjectDic = [NSJSONSerialization JSONObjectWithData:dataDic
                                                       options:NSJSONReadingAllowFragments
                                                         error:&errDic];
    
    return jsonObjectDic;
}


-(void)transition:(UIView*)view AndTime:(float)time{
    CATransition * transition = [CATransition animation];
    transition.duration = time;
    transition.type = kCATransitionFromTop;
    transition.subtype = kCATransitionFromRight;
    [view.window.layer addAnimation:transition forKey:nil];
}

+(void)isLogin:(UIViewController *)target andPush:(UIViewController *)next
{
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    
    NSString *string = [userDefaults objectForKey:@"login"];
    
    //    self.isLogin =
    
    if (string == nil ) {
        
        LoginViewController *loginVC = [[LoginViewController alloc]init];
        UINavigationController * loginNC = [[UINavigationController alloc]initWithRootViewController:loginVC];
        
        [target presentViewController:loginNC animated:YES completion:nil];
        
    }  else {
        [target.navigationController pushViewController:next animated:YES];
    }
}

+(void)showAlertViewAndAnimated:(BOOL)animated andString:(NSString *)string
{
    UIWindow *window = [[UIApplication sharedApplication].delegate window];
    
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
    view.backgroundColor = [UIColor blackColor];
    [window addSubview:view];
    
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10, 10, window.frame.size.width/2.0, 20)];
    label.text = string;
    label.textColor = [UIColor whiteColor];
    label.font = [UIFont systemFontOfSize:15];
    label.numberOfLines = 0;
    label.textAlignment = NSTextAlignmentCenter;
    CGRect rect = [label.text boundingRectWithSize:CGSizeMake(window.frame.size.width/2.0, 200) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15]} context:nil];
    label.frame = CGRectMake(15, 5, rect.size.width + 20, rect.size.height + 10);
    view.frame = CGRectMake(0, 0, rect.size.width + 50, rect.size.height + 20);
    [view addSubview:label];
    view.layer.cornerRadius = 10;
    
    view.center = window.center;
    
    if (animated) {
        view.alpha = 0;
        [window addSubview:view];
        
        [UIView animateWithDuration:0.3 animations:^{
            view.alpha = 0.78;
        } completion:^(BOOL finished) {
            
            
        }];
    }
    else {
        [window addSubview:view];
    }
    
    //延迟执行
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [view removeFromSuperview];
        
    });
    
}





@end
